package cn.bulgat.spring.web.service.impl;

import cn.bulgat.common.exception.CustomException;
import cn.bulgat.common.exception.ThrowUtils;
import cn.bulgat.common.id.IIdGenerator;
import cn.bulgat.common.model.RespCode;
import cn.bulgat.spring.web.config.AppConfig;
import cn.bulgat.spring.web.constant.CommonConstant;
import cn.bulgat.spring.web.constant.UserConstant;
import cn.bulgat.spring.web.mapper.UserMapper;
import cn.bulgat.spring.web.model.entity.User;
import cn.bulgat.spring.web.model.req.user.AddReq;
import cn.bulgat.spring.web.model.req.user.QueryReq;
import cn.bulgat.spring.web.model.enums.UserRole;
import cn.bulgat.spring.web.model.vo.LoginUserVO;
import cn.bulgat.spring.web.model.vo.UserVO;
import cn.bulgat.spring.web.service.UserService;
import cn.bulgat.spring.web.utils.CryptoUtils;
import cn.bulgat.spring.web.utils.SqlUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static cn.bulgat.spring.web.constant.UserConstant.*;
/**
 * 用户服务实现
 *
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private IIdGenerator<Long> idGenerator;
    @Resource
    private AppConfig appConfig;
    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "ewhfiwuefhiewhfiewfiewjfiewjfiewjfi";

    @Override
    public long register(String username, String password, String confirmPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(username, password, confirmPassword)) {
            throw new CustomException(RespCode.PARAMS_ERROR, "参数为空");
        }
        if (username.length() < 4) {
            throw new CustomException(RespCode.PARAMS_ERROR, "用户昵称过短");
        }
        if (password.length() < 8 || confirmPassword.length() < 8) {
            throw new CustomException(RespCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!password.equals(confirmPassword)) {
            throw new CustomException(RespCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        String account= appConfig.getName()
                .concat("-")
                .concat(idGenerator.nextId().toString());
        synchronized (username.intern()) {
            // 昵称不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new CustomException(RespCode.PARAMS_ERROR, "昵称重复");
            }
            // 2. 加密
            String salt = CryptoUtils.generateSalt(SALT_BYTE_LENGTH);
            String hash = CryptoUtils.sha256WithSalt(password, salt);

            // 3. 插入数据
            User user = User.builder()
                    .username(username)
                    .account(account)
                    .salt(salt)
                    .hash(hash)
                    .build();
            boolean save = this.save(user);
            if (!save) {
                throw new CustomException(RespCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public LoginUserVO login(String username, String password, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(username, password)) {
            throw new CustomException(RespCode.PARAMS_ERROR, "参数为空");
        }
        if (username.length() < 4) {
            throw new CustomException(RespCode.PARAMS_ERROR, "昵称错误");
        }
        if (password.length() < 8) {
            throw new CustomException(RespCode.PARAMS_ERROR, "密码错误");
        }

        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, uasername cannot match password");
            throw new CustomException(RespCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 核对密码hash
        String salt = user.getSalt();
        String hash = user.getHash();
        boolean verified = CryptoUtils.verifyPassword(password, salt, hash);
        if (!verified) {
            log.info("user login failed, username cannot match password");
            throw new CustomException(RespCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new CustomException(RespCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new CustomException(RespCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取当前登录用户（允许未登录）
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUserPermitNull(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        return this.getById(userId);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        return isAdmin(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRole.ADMIN.getCode().equals(user.getRole());
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean logout(HttpServletRequest request) {
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null) {
            throw new CustomException(RespCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(QueryReq queryReq) {
        if (queryReq == null) {
            throw new CustomException(RespCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = queryReq.getId();
        String username = queryReq.getUsername();
        String profile = queryReq.getProfile();
        Integer role = queryReq.getRole();
        String sortField = queryReq.getSortField();
        String sortOrder = queryReq.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(!ObjectUtils.isEmpty(role), "role", role);
        queryWrapper.like(StringUtils.isNotBlank(profile), "profile", profile);
        queryWrapper.like(StringUtils.isNotBlank(username), "username", username);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public boolean hasAuth(User user,UserRole needRole){
        // 当前登录用户
        // 不需要权限，放行
        if (needRole == null) {
            return true;
        }
        if (user==null){
            throw new CustomException(RespCode.NOT_LOGIN_ERROR);
        }
        // 必须有该权限才通过
        UserRole userRole = UserRole.getByCode(user.getRole());
        if (userRole == null) {
            throw new CustomException(RespCode.NO_AUTH_ERROR);
        }
        // 如果被封号，直接拒绝
        if (UserRole.BAN.equals(userRole)) {
            throw new CustomException(RespCode.NO_AUTH_ERROR);
        }
        // 必须有管理员权限
        if (UserRole.ADMIN.equals(needRole)) {
            // 用户没有管理员权限，拒绝
            if (!UserRole.ADMIN.equals(userRole)) {
                throw new CustomException(RespCode.NO_AUTH_ERROR);
            }
        }
        return true;
    }

    @Override
    public boolean hasAuthPermitNull(User user, UserRole needRole){
        // 当前登录用户
        if (needRole == null) {
            return true;
        }
        if (user==null){
            return false;
        }
        // 必须有该权限才通过
        UserRole userRole = UserRole.getByCode(user.getRole());
        if (userRole == null) {
            return false;
        }
        // 如果被封号，直接拒绝
        if (UserRole.BAN.equals(userRole)) {
            return false;
        }
        // 必须有管理员权限
        if (UserRole.ADMIN.equals(needRole)) {
            // 用户没有管理员权限，拒绝
            if (!UserRole.ADMIN.equals(userRole)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Long addUser(AddReq addReq) {
        User user = new User();
        BeanUtils.copyProperties(addReq, user);
        String salt = CryptoUtils.generateSalt(SALT_BYTE_LENGTH);
        String hash = CryptoUtils.sha256WithSalt(DEFAULT_PASSWORD, salt);
        user.setSalt(salt);
        user.setHash(hash);
        boolean result = this.save(user);
        ThrowUtils.throwIf(!result, RespCode.OPERATION_ERROR);
        return user.getId();
    }
}
